<?php
/*
 * @package Webhosting Component
 * @copyright Copyright (C) 2007 Jonas Brand. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 * Official website: http://wh-com.de
 */

/*
* Sicherstellen, dass das Script nicht direkt aufgerufen wird
*/
defined( '_VALID_MOS' ) or die('Direct Access to this acript is not allowed');

#if (!($acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'all' ) | $acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'component        s', 'com_webhosting' ))) {
#mosRedirect( 'index2.php', _NOT_AUTH );
#}

define( 'LANGDIR', $mosConfig_absolute_path.'/administrator/components/com_webhosting/language/' );
require_once($mainframe->getPath('class'));
require_once($mainframe->getPath('admin_html'));

if (defined( '_JEXEC' )) {
    JToolBarHelper::preferences( 'com_webhosting', 600 );
}

/*
* Definition der globalen Variablen
* benoetigt fuer Joomla 1.5 aufgrund beschraenktem Gueltigkeitsbereich
*/
global $params, $database, $vhcsdb, $mainframe, $componentid, $my, $plantable, $ordertable, $mode;

/*
* Sprachfile laden
* Wenn vorhanden, wird die in Joomla eingestellte Sprache verwendet
* Ansonsten wird Englisch verwendet
*/

$lang=$mainframe->getCfg('lang');
if($lang == 'germani') $lang = 'german';
if(file_exists(LANGDIR.$lang.".php")) {
    include_once(LANGDIR.$lang.".php");
} else {
    include_once(LANGDIR."english.php");
}

/*
* Konfigurations-Parameter laden
*/
// get id of component
$query = "SELECT a.id"
. "\n FROM #__components AS a"
. "\n WHERE ( a.admin_menu_link = 'option=com_webhosting' OR a.admin_menu_link = 'option=com_webhosting' )"
. "\n AND a.option = 'com_webhosting'"
;
$database->setQuery( $query );
$componentid = $database->loadResult();
// load the row from the db table
$row = new mosComponent( $database );
$row->load( $componentid );
// get params definitions

if( file_exists( LANGDIR.'/params_'.$lang.'.xml' ) ) {
    $params = new mosParameters( $row->params, LANGDIR.'/params_'.$lang.'.xml', 'component' );
} else {
    $params = new mosParameters( $row->params, $mosConfig_absolute_path.'/administrator/components/com_webhosting/config.xml', 'component' );
}

/*
* Je nach Modus Datenbank-Objekt setzen und Tabellennamen definieren
*/
$mode=$params->get('mode','joomla');
if($mode=="vhcs2") {
	$vhcsdb = @new database( $params->get('mysql-host','localhost'),
							   $params->get('mysql-user',''),
							   $params->get('mysql-pass',''),
							   $params->get('mysql-db',''), '', false );
	$vhcsdb->setQuery("SELECT * FROM hosting_plans LIMIT 1");
	@$vhcsdb->query();
	$error=$vhcsdb->getErrorMsg();
	$vhcsdb->setQuery("SELECT * FROM orders LIMIT 1");
	@$vhcsdb->query();
	$error.=$vhcsdb->getErrorMsg();
	if($error=='')
	{
	    $plantable="hosting_plans";
		$ordertable="orders";
	}
	else
	{
		echo "<div style='text-align:center; color: red; font-size:20px; margin-top:20px;'>".LANG_VHCS_CONNECTION_FAILED."</div>";
		$mode='joomla';
	}
}
if($mode!=="vhcs2") {
    $vhcsdb=$database;
    $plantable="#__wh_plans";
    $ordertable="#__wh_orders";
}

if(!function_exists('josGetArrayInts')) {
function josGetArrayInts( $name, $type=NULL ) {
	if ( $type == NULL ) {
		$type = $_POST;
	}

	$array = mosGetParam( $type, $name, array(0) );

	mosArrayToInts( $array );

	if (!is_array( $array )) {
		$array = array(0);
	}

	return $array;
}
}

$cid = josGetArrayInts( 'cid' );

if(!$task)
	$task="listPlans";

switch ($task) {
// Categories
	case "listCats": listCats($option); break;
    case "editCat": editCat( intval( mosGetParam($_GET,'id') ), $option); break;
    case "addCat": editCat( '0', $option); break;
    case "orderCatsUp": orderCats(intval ($cid[0]),'-1',$option); break;
    case "orderCatsDown": orderCats(intval ($cid[0]),'1',$option); break;
    case "saveCat": saveCat($option); break;
    case "cancelCat": mosRedirect("index2.php?option=$option&task=listCats"); break;
    case "removeCats": removeCats($cid,$option); break;
// Features
    case "listFeatures": listFeatures($option); break;
    case "editFeature": editFeature( intval( mosGetParam($_GET,'id') ), $option); break;
    case "addFeature": editFeature( '0', $option); break;
    case "orderFeaturesUp": orderFeatures(intval($cid[0]),'-1',$option); break;
    case "orderFeaturesDown": orderFeatures(intval($cid[0]),'1',$option); break;
    case "saveFeature": saveFeature($option); break;
    case "cancelFeature": mosRedirect("index2.php?option=$option&task=listFeatures"); break;
    case "removeFeatures": removeFeatures($cid,$option); break;
    case "standardFeature": standardFeature(intval($cid[0]),$option); break;
// Plans
    case "cancelPlan": mosRedirect("index2.php?option=$option&task=listPlans"); break;
    case "listPlans": listPlans($option); break;
    case "editPlan": editPlan( intval(mosGetParam($_GET,'id') ),$option); break;
    case "addPlan": editPlan( '0', $option); break;
    case "orderPlansUp": orderPlans(intval($cid[0]),'-1',$option); break;
    case "orderPlansDown": orderPlans(intval($cid[0]),'1',$option); break;
    case "savePlan": savePlan($option); break;
    case "removePlans": removePlans($cid,$option); break;
    case "publishPlan": publishPlan(intval($cid[0]),$option); break;
// Config
    case "showConfig": showConfig($option); break;
    case "saveConfig": saveConfig($option); break;
// Load Sampledata
    case "loadSampledata": loadSampledata($option); break;
    case "upgradeDatabase": upgradeDatabase($option); break;
}

function listCats($option) {
	global $database;

	$database->setQuery("SELECT * FROM #__wh_featurecat ORDER BY ordering");
	$rows=$database->loadObjectList();

	HTML_webhosting::listCats($option, $rows);
	}

function orderCats($uid,$inc,$option) {
    global $database;
    $row = new wh_featurecat( $database );
    $row->load( (int)$uid );
    $row->updateOrder();
    $row->move( $inc,"" );
    $row->updateOrder();
    mosRedirect( "index2.php?option=$option&task=listCats" );
    }

function editCat($id,$option) {
    global $database, $my;

    $row=new wh_featurecat( $database );
    $row->load( (int)$id);
    if($id) {
        $row->checkout($my->id);
    }
    else {
        $database->setQuery("SELECT MAX(ordering) FROM #__wh_featurecat");
        $row->ordering=$database->loadResult()+1;
    }
    HTML_webhosting::editCat( $row, $option );
}

function saveCat($option) {
    global $database;
    $row=new wh_featurecat($database);
    $row->bind($_POST);
    $row->store();
    mosRedirect("index2.php?option=$option&task=listCats","Saved");
}

function removeCats($cid, $option) {
    global $database;
    if(count( $cid )) {
        $cids = implode( ',', $cid );
        $database->setQuery("DELETE FROM #__wh_featurecat WHERE id IN ( ".$database->getEscaped($cids)." )");
        $database->query() or die("MySQL Error");
    }
    mosRedirect("index2.php?option=$option&task=listCats");
}

function showConfig($option) {
	global $params, $database, $mainframe, $componentid;
	if (defined( '_JEXEC' )) {
	  mosRedirect( 'index2.php?option='.$option, LANG_CONFIG_JOOMLA15 );
	} else {
	  // load the row from the db table
	  #$row = new mosComponent( $database );
	  #$row->load( $componentid );
	  $params->get('mode');
	  // get params definitions
	  HTML_webhosting::showConfig( $option, $params, $componentid );
	}
}

function saveConfig( $option ) {
	global $database;

	$params = mosGetParam( $_POST, 'params', '' );
	if (is_array( $params )) {
		$txt = array();
		foreach ($params as $k=>$v) {
			$txt[] = "$k=$v";
		}
		$_POST['params'] = mosParameters::textareaHandling( $txt );
	}

	$id = intval( mosGetParam( $_POST, 'id', '17' ) );
	$row = new mosComponent( $database );
	$row->load( $id );

	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
    $msg = 'Setting successfully Saved';
    mosRedirect( 'index2.php?option='.$option."&task=showConfig", $msg );
}

function listFeatures($option) {
	global $database;

	$database->setQuery("SELECT f.id, f.name, f.ordering, f.standard, c.name as catname, c.ordering as catordering FROM #__wh_features as f, #__wh_featurecat as c WHERE f.cat = c.id ORDER BY c.ordering,f.ordering");
	$rows=$database->loadObjectList();

	HTML_webhosting::listFeatures($option, $rows);
	}

function orderFeatures($uid,$inc,$option) {
    global $database;

    $database->setQuery("SELECT cat FROM #__wh_features WHERE id ='".intval($uid)."' LIMIT 1");
    $cat = $database->loadResult();

    $row = new wh_features( $database );
    $row->load( (int)$uid );
    $row->updateOrder("cat = ".$cat);
    $row->move( $inc,"cat = ".$cat );
    $row->updateOrder("cat = ".$cat);
    mosRedirect( "index2.php?option=$option&task=listFeatures" );
    }

function standardFeature($uid,$option) {
    global $database;
    $database->setQuery("SELECT standard FROM #__wh_features WHERE id='".intval($uid)."'");
    $standard=$database->loadResult();
    if($standard==0) {
        $database->setQuery("UPDATE #__wh_features SET standard='1' WHERE id='".intval($uid)."'");
        $database->query();
        }
    else {
        $database->setQuery("UPDATE #__wh_features SET standard='0' WHERE id='".intval($uid)."'");
        $database->query();
        }
    mosRedirect( "index2.php?option=$option&task=listFeatures" );
    }

function editFeature($id,$option) {
    global $database, $my;

    $row=new wh_features( $database );
    $row->load( (int)$id);
    if($id) {
        $row->checkout($my->id);
    }
    else {
        $database->setQuery("SELECT MAX(ordering) FROM #__wh_features");
        $row->ordering=$database->loadResult()+1;
    }

    $database->setQuery("SELECT id, name FROM #__wh_featurecat ORDER BY ordering");
    $cats=$database->loadObjectList();

    HTML_webhosting::editFeature( $row, $cats, $option );
}

function saveFeature($option) {
    global $database;
    $row=new wh_features($database);
    $row->bind($_POST);
    $row->store();
    mosRedirect("index2.php?option=$option&task=listFeatures",LANG_SAVED);
}

function removeFeatures($cid, $option) {
    global $database;
    if(count( $cid )) {
        $cids = implode( ',', $cid );
        $database->setQuery("DELETE FROM #__wh_features WHERE id IN ( ".$database->getEscaped($cids)." )");
        $database->query() or die("MySQL Error");
    }
    mosRedirect("index2.php?option=$option&task=listFeatures");
}

function listPlans($option) {
	global $database,$vhcsdb,$plantable,$mode;

    if($mode=="vhcs2") {
	    $database->setQuery("SELECT p.id AS id, p.id_vhcs AS id_vhcs, c.id AS catid, c.title AS cat, p.published as published ".
	    					"FROM #__wh_plans AS p ".
	    					"LEFT JOIN #__categories AS c ON c.id = p.catid ".
	    					"ORDER BY c.ordering, p.ordering"
	    					);
	    $rows=$database->loadObjectList();
        $i=0;
        foreach($rows as $row)
        {
            $vhcsdb->setQuery("SELECT name FROM $plantable WHERE id='".$row->id_vhcs."'");
            $vhcsdb->loadObject($row2);
            $rows[$i]->name=$row2->name;
            $i++;
        }
    }
    else {
	    $database->setQuery("SELECT p.id AS id, p.name AS name, c.id AS catid, c.title AS cat, p.published AS published ".
	    					"FROM #__wh_plans AS p ".
	    					"LEFT JOIN #__categories AS c ON c.id = p.catid ".
	    					"ORDER BY c.ordering, p.ordering"
	    					);
        $rows=$database->loadObjectList();
    }

	HTML_webhosting::listPlans($option, $rows);
}

function orderPlans($uid,$inc,$option) {
    global $database;
    $row = new wh_plans( $database );
    $row->load( (int)$uid );
    if($row->catid !== 0) {
	$row->updateOrder("catid=".$row->catid);
	$row->move( $inc,"catid=".$row->catid );
	$row->updateOrder("catid=".$row->catid);
    } else {
	$row->updateOrder('');
	$row->move( $inc );
	$row->updateOrder('');
    }
    mosRedirect( "index2.php?option=$option&task=listPlans" );

/*

    global $database;

    $database->setQuery("SELECT cat FROM #__wh_features WHERE id ='".intval($uid)."' LIMIT 1");
    $cat = $database->loadResult();

    $row = new wh_features( $database );
    $row->load( (int)$uid );
    $row->updateOrder("cat = ".$cat);
    $row->move( $inc,"cat = ".$cat );
    $row->updateOrder("cat = ".$cat);
    mosRedirect( "index2.php?option=$option&task=listFeatures" );*/
}

function publishPlan($id,$option) {
    global $database;
    $database->setQuery("SELECT published FROM #__wh_plans WHERE id='".intval($id)."'");
    $published=$database->loadResult();
    if($published==0) {
        $database->setQuery("UPDATE #__wh_plans SET published='1' WHERE id='".intval($id)."'");
        }
    else {
        $database->setQuery("UPDATE #__wh_plans SET published='0' WHERE id='".intval($id)."'");
        }
    $database->query();
    mosRedirect( "index2.php?option=$option&task=listPlans" );
}

function editPlan($id,$option) {
    global $database, $vhcsdb, $my, $mode;

    $row=new wh_plans( $database );
    $row->load( (int)$id);
    if($id) {
        $row->checkout($my->id);
    }

    if($mode=="vhcs2") {
        $row2=new hosting_plans( $vhcsdb );
        $row2->load( (int)$row->id_vhcs );
        $vhcsdb->setQuery("SELECT admin_id,admin_name FROM admin WHERE admin_type='reseller'");
        $reseller=$vhcsdb->loadObjectList();
    }
    else {
        $row2=new wh_plans2 ( $database );
        $row2->load( (int)$id );
    }

    $cats = mosAdminMenus::ComponentCategory( 'catid', 'com_webhosting', $row->catid );

    $database->setQuery("SELECT f.id, f.name, f.ordering, f.standard, c.ordering as catordering FROM #__wh_features as f, #__wh_featurecat as c WHERE f.cat = c.id ORDER BY c.ordering,f.ordering");
    $features=$database->loadObjectList();

    HTML_webhosting::editPlan( $row, $row2, $features, $reseller, $cats, $mode, $option );
}

function savePlan($option) {
    global $database, $mode, $vhcsdb, $plantable;
    $_POST['features']='-'.implode("-",$_POST['features']).'-';
    $_POST['features_short']='-'.implode('-',$_POST['features_short']).'-';
    $_POST['php']==1 ? $_POST['php']='_yes_' : $_POST['php']='_no_';
    $_POST['cgi_perl']==1 ? $_POST['cgi_perl']='_yes_' : $_POST['cgi_perl']='_no_';
    $_POST['props']=$_POST['php'].';'.
                    $_POST['cgi_perl'].';'.
                    $_POST['subdomains'].';'.
                    $_POST['aliases'].';'.
                    $_POST['mailaccounts'].';'.
                    $_POST['ftpaccounts'].';'.
                    $_POST['dbaccounts'].';'.
                    $_POST['dbusers'].';'.
                    $_POST['traffic'].';'.
                    $_POST['webspace'].';';
    // get ordering
    if( $_POST['ordering'] == '' ) {
        $database->setQuery("SELECT MAX(ordering) FROM #__wh_plans WHERE cat = '".intval($_POST['cat'])."'");
        $row->ordering=$database->loadResult()+1;
    }

    if($mode=='vhcs2')
    {
        $array=$_POST;
        $array['id']=$array['id_vhcs'];
        $row=new hosting_plans($vhcsdb);
        if($array['newvhcs']=='1' || $array['id_vhcs']<=0) {
            $array['id']=0;
        }
        $row->bind($array);
        $row->store();
        if($array['newvhcs']=='1' || $array['id_vhcs']<=0) {
            $vhcsdb->setQuery("SELECT id FROM $plantable WHERE name='".$array['name']."' ORDER BY id DESC LIMIT 1");
            $_POST['id_vhcs']=$vhcsdb->loadResult();
        }
        $row=new wh_plans($database);
        $row->bind($_POST);
        $row->store();
    }
    else
    {
        $row=new wh_plans_full($database);
        $row->bind($_POST);
        $row->store();
    }

    mosRedirect("index2.php?option=$option&task=listPlans",LANG_SAVED);
}

function removePlans($cid, $option) {
    global $database, $vhcsdb, $plantable, $mode;
    if(count( $cid )) {
        $cids = implode( ',', $cid );
        if($mode=="vhcs2")
        {
            $database->setQuery("SELECT id_vhcs FROM #__wh_plans WHERE id IN ( $cids )");
            $vhcsids=$database->loadObjectList();
            foreach( $vhcsids as $vhcsid )
            {
                $vhcsdb->setQuery("DELETE FROM $plantable WHERE id='".$vhcsid->id_vhcs."'");
                $vhcsdb->query() or die("MySQL Error");
            }
        }
        $database->setQuery("DELETE FROM #__wh_plans WHERE id IN ( ".$database->getEscaped($cids)." )");
        $database->query() or die("MySQL Error");
    }
    mosRedirect("index2.php?option=$option&task=listPlans");
}

function loadSampledata($option) {
	global $database;
	$sampledata=explode("---",LANG_SAMPLEDATA);
        $queries='';
        $errors='';
	foreach($sampledata as $sql) {
		$database->setQuery($sql);
		$queries.=$sql.'<br/><br/>';
		if(!$database->query()) {
			$errors.=$database->getErrorMsg().'<br/><br/>';
		}
	}
	if($errors == '') {
		mosRedirect("index2.php?option=$option",LANG_SAMPLEDATA_LOADED);
	}
	else {
		echo "<h2>".LANG_SAMPLEDATA_NOTLOADED."</h2>";
		echo "<h3>Errors:</h3>";
		echo $errors;
		echo "<h3>MySQL-Queries:</h3>";
		echo $queries;
                // Comment this line to activate debugging
                mosRedirect("index2.php?option=$option",LANG_SAMPLEDATA_NOTLOADED);
	}
}

function upgradeDatabase($option) {
    global $database;
    $errors='';
    $query="ALTER TABLE #__wh_orders ADD street2 VARCHAR( 200 ) NOT NULL COMMENT 'Total Fees' AFTER street1";
    $queries="<br/><br/>".$query;
    $database->setQuery($query);
    if(!$database->query()) {
        $errors.=$database->getErrorMsg().'<br/><br/>';
    }

    $query="ALTER TABLE #__wh_plans ADD tldprices VARCHAR( 255 ) NOT NULl AFTER tlds";
    $queries.="<br/><br/>".$query;
    $database->setQuery($query);
    if(!$database->query()) {
        $errors.=$database->getErrorMsg().'<br/><br/>';
    }

    $query="UPDATE #__wh_plans SET payment='12' WHERE payment NOT IN ('1','3','6','12','24')";
    $queries.="<br/><br/>".$query;
    $database->setQuery($query);
    if(!$database->query()) {
        $errors.=$database->getErrorMsg().'<br/><br/>';
    }

    $query="UPDATE #__wh_plans SET tldprices='9.99,11.99' WHERE tldprices = ''";
    $queries.="<br/><br/>".$query;
    $database->setQuery($query);
    if(!$database->query()) {
        $errors.=$database->getErrorMsg().'<br/><br/>';
    }

    $query="ALTER TABLE `#__wh_plans` CHANGE `payment` `payment` TINYINT( 2 ) NULL DEFAULT NULL";
    $queries.="<br/><br/>".$query;
    $database->setQuery($query);
    if(!$database->query()) {
        $errors.=$database->getErrorMsg().'<br/><br/>';
    }

    $query="UPDATE #__wh_features SET value='[billing_cycle]' WHERE value='[payment]'";
    $queries.="<br/><br/>".$query;
    $database->setQuery($query);
    if(!$database->query()) {
        $errors.=$database->getErrorMsg().'<br/><br/>';
    }

    $query="ALTER TABLE #__wh_plans ADD `catid` INT UNSIGNED NOT NULL DEFAULT '0' AFTER `id_vhcs`;";
    $queries.="<br/><br/>".$query;
    $database->setQuery($query);
    if(!$database->query()) {
        $errors.=$database->getErrorMsg().'<br/><br/>';
    }

    if($errors !== '') {
        echo "<h2>".LANG_UPGRADE_NOTOK."</h2>";
        echo "<h3>Errors:</h3>";
        echo $errors;
        echo "<h3>MySQL-Queries:</h3>";
        echo $queries;
        // Comment this line to activate debugging
        mosRedirect("index2.php?option=$option",LANG_UPGRADE_NOTOK);
    } else {
        mosRedirect("index2.php?option=$option",LANG_UPGRADE_OK);
    }
}
?>
